package com.upcode.weighing.util.ops;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 时间工具
 */
public class TimeUtil {

    //超过numYear年==================start
    public static Boolean DateCompare(String startTime, String endTime, int numYear) {
        boolean flag = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        try {
            Date time1 = sdf.parse(startTime);
            Date time2 = sdf.parse(endTime);
            Date time3 = add(time1, Calendar.YEAR, numYear);
            if (time3.getTime() < time2.getTime()) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    private static Date add(final Date date, final int calendarField, final int amount) {
        if (date == null) {
            return null;
        }
        final Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }
    //================================end

    /**
     * 将20211112165557转为date
     *
     * @param str
     * @return
     * @throws ParseException
     */
    public static String strToDate(String str) throws ParseException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime ldt = LocalDateTime.parse(str, dtf);
        DateTimeFormatter fa = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return ldt.format(fa);
    }

    /**
     * 判断两个时间大小
     *
     * @param str1
     * @param str2
     * @return
     * @throws ParseException
     */
    public static Boolean checkTime(String str1, String str2) throws ParseException {
        Boolean ok = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date a = sdf.parse(str1);
        Date b = sdf.parse(str2);
        if (a.getTime() - b.getTime() < 0) {
            ok = true;
        }
        return ok;
    }

    /**
     * 获取两个时间相隔的天数
     *
     * @param time
     * @param time1
     * @return
     * @throws Exception
     */
    public static Long checkTime2(String time, String time1) {
        Long daysBetween = 0L;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d1 = sdf.parse(time);
            Date d2 = sdf.parse(time1);
            daysBetween = (d2.getTime() - d1.getTime() + 1000000) / (60 * 60 * 24 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return daysBetween;
    }

    public static void main(String[] args) {
        Long day = TimeUtil.checkTime2("2021-10-17", "2021-12-16");
        System.out.println(day);
    }

    /**
     * 比较年
     *
     * @param str1
     * @param str2
     * @return
     * @throws ParseException
     */
    public static Boolean checkTime1(String str1, String str2) throws ParseException {
        Boolean ok = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date a = sdf.parse(str1);
        Date b = sdf.parse(str2);
        if (a.getTime() - b.getTime() < 0) {
            ok = true;
        }
        return ok;
    }

    /**
     * 获取到的字符串时间转为yyyy
     *
     * @param str 字符串时间
     * @return
     * @throws ParseException
     */
    public static String timeToStr(String str) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date d = sdf.parse(str);
        return sdf.format(d);
    }


    /**
     * 获取当前年
     *
     * @return
     */
    public static String getDqYear() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy");
        return dtf.format(time);
    }

    /**
     * 获取下一年
     *
     * @return
     */
    public static String getNextYear() {
        Integer i = Integer.parseInt(getDqYear()) + 1;
        return i.toString();
    }

    /**
     * 获取当前月
     *
     * @return
     */
    public static String getDqMonth() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM");
        return dtf.format(time);
    }

    /**
     * 获取当前日
     *
     * @return
     */
    public static String getDqDay() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd");
        return dtf.format(time);
    }

    /**
     * 获取当前时间转为 yyyy-MM
     *
     * @return
     */
    public static String time1() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM");
        return dtf.format(time);
    }

    /**
     * 获取当前时间转为 yyyy-MM-dd
     *
     * @return
     */
    public static String time2() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return dtf.format(time);
    }

    /**
     * 获取当前时间转为 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String time3() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dtf.format(time);
    }

    /**
     * 转化当前时间为xxxx年xx月xx日
     *
     * @return
     */
    public static String time4() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        return dtf.format(time);
    }

    /**
     * yyyy年MM月dd日转为yyyy-MM-dd
     *
     * @param str
     * @return
     * @throws ParseException
     */
    public static String time5(String str) throws ParseException {
        Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(str);
        String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
        return time;
    }

    /**
     * 获取当前时间MM-dd
     *
     * @return
     * @throws ParseException
     */
    public static String time6() throws ParseException {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd");
        return dtf.format(time);
    }

    /**
     * 将字符串时间转为LocalDateTime
     *
     * @param str
     * @return
     */
    public static LocalDateTime time6(String str) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(str, df);
        return ldt;
    }

    /**
     * 获取日期
     *
     * @param index
     * @return
     */
    public static String time7(Integer index) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -index);
        String res = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return res;
    }

    /**
     * h获取今日起始日期和结束日期
     *
     * @return
     */
    public static String[] getToday() {
        String startTime = time10();
        String endTime = time3();
        return new String[]{startTime, endTime};
    }

    /**
     * 获取昨日起始日期和结束日期
     *
     * @return
     */
    public static String[] getYesterdayStartAndEnd() {
        String startTime = time7(1) + " 00:00:00";
        String endTime = time10();
        return new String[]{startTime, endTime};
    }

    /**
     * 获取近七天起始日期和结束日期
     *
     * @return
     */
    public static String[] getLastSevenDays() {
        String startTime = time7(6) + " 00:00:00";
        String endTime = time3();
        return new String[]{startTime, endTime};
    }

    /**
     * 获取近30天起始日期和结束日期
     *
     * @return
     */
    public static String[] getThirtyDays() {
        String startTime = time7(29) + " 00:00:00";
        String endTime = time3();
        return new String[]{startTime, endTime};
    }


    /**
     * 时间搜索
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param types     //类型 1:今日 2:昨日 3:最近7天 4:最近30天
     * @return
     */
    public static String[] time8(String startTime, String endTime, Integer types) {
        String[] res = null;
        if (OtherUtills.checkStr(startTime) && OtherUtills.checkStr(endTime)) {
            res = new String[]{startTime, endTime};
            return res;
        }
        if (types == null) {
            res = new String[]{"", ""};
            return res;
        }
        //类型 1:今日 2:昨日 3:最近7天 4:最近30天
        if (types == 1) {
            res = getToday();
        } else if (types == 2) {
            res = getYesterdayStartAndEnd();
        } else if (types == 3) {
            res = getLastSevenDays();
        } else if (types == 4) {
            res = getThirtyDays();
        }
        return res;
    }

    /**
     * 获取当前时间
     *
     * @return yyyy-MM-dd 00:00:00
     */
    public static String time10() {
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return dtf.format(time) + " 00:00:00";
    }

    /**
     * 获取两个日期之间相隔的月份
     *
     * @param start
     * @param end
     * @return
     */
    public static int getMonth(Date start, Date end) {
        if (start.after(end)) {
            Date t = start;
            start = end;
            end = t;
        }
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(start);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(end);
        Calendar temp = Calendar.getInstance();
        temp.setTime(end);
        temp.add(Calendar.DATE, 1);

        int year = endCalendar.get(Calendar.YEAR)
                - startCalendar.get(Calendar.YEAR);
        int month = endCalendar.get(Calendar.MONTH)
                - startCalendar.get(Calendar.MONTH);

        if ((startCalendar.get(Calendar.DATE) == 1)
                && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month + 1;
        } else if ((startCalendar.get(Calendar.DATE) != 1)
                && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month;
        } else if ((startCalendar.get(Calendar.DATE) == 1)
                && (temp.get(Calendar.DATE) != 1)) {
            return year * 12 + month;
        } else {
            return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
        }
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param time1 startTime 开始时间
     * @param time2 endTime 结束时间
     * @return
     */
    public static boolean isEffectiveDate(String time1, String time2) throws Exception {
        //Date nowTime, Date startTime, Date endTime
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        Date nowTime = sdf.parse(time6());
        Date startTime = sdf.parse(time1);
        Date endTime = sdf.parse(time2);
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /*处理无分隔符的日期*/
    //主方法
    public static String convJsonDateToString(String jsonDate, String stringTemplate) {

        String resultString = null;
        try {
            Calendar cldCalendar = convToCalender(jsonDate, "yyyyMMddhhmmss");
            resultString = convToString(cldCalendar, stringTemplate);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resultString;
    }

    public static String convJsonDateToString(String jsonDate, String jsonTemplate, String stringTemplate) {

        String resultString = null;
        try {
            Calendar cldCalendar = convToCalender(jsonDate, jsonTemplate);
            resultString = convToString(cldCalendar, stringTemplate);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resultString;
    }

    // 把指定格式的日期字符串转日期类型
    public static Calendar convToCalender(String str, String template) {

        SimpleDateFormat sdf;
        Date date;
        Calendar cltResult = Calendar.getInstance();

        sdf = new SimpleDateFormat(template, Locale.getDefault());
        try {
            date = sdf.parse(str);

            cltResult.setTime(date);

        } catch (Exception ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }

        return cltResult;
    }

    // 把日期转指定格式字符串
    public static String convToString(Calendar cld, String template) {
        String resultString = null;
        try {
            Date date = cld.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat(template, Locale.getDefault());
            resultString = sdf.format(date);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resultString;
    }
    /*===========================================================================*/


    /**
     * 获取两个日期中的所有天数
     *
     * @param startTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> huoquDate(String startTime, String endTime) {
        List<String> days = new ArrayList<String>();
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
            Collections.sort(days);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    public static List<String> huoquDate1(String startTime, String endTime) {
        List<String> days = new ArrayList<String>();
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date start = dateFormat.parse(startTime.substring(0,10));
            Date end = dateFormat.parse(endTime.substring(0,10));
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
            Collections.sort(days);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }


    /**
     * @param time
     * @param n    n是几 就是time的上几个月
     * @return
     * @throws ParseException
     */
    public static String getPrevMonthDate(String time, int n) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        Date date = new SimpleDateFormat("yyyy-MM").parse(time);
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - n);
        return new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
    }

    /**
     * @param time
     * @param n    n是几 就是time的下几个月
     * @return
     * @throws ParseException
     */
    public static String getDownMonthDate(String time, int n) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        Date date = new SimpleDateFormat("yyyy-MM").parse(time);
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + n);
        return new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
    }

}
